package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.order.dto.CreateOrderRequest;
import com.cskaoyan.order.dto.CreateOrderResponse;
import com.cskaoyan.order.dto.OrderListRequest;
import com.cskaoyan.order.dto.OrderListResponse;
import com.cskaoyan.order.service.OrderCoreService;
import com.cskaoyan.order.service.OrderQueryService;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
public class OrderCreateController {

    @Autowired
    OrderCoreService orderCoreService;

    @Autowired
    OrderQueryService orderQueryService;

    @PostMapping("/shopping/order")
    public ResponseData createOrder(@RequestBody CreateOrderRequest request, HttpServletRequest httpRequest) {
        //是否需要自行设置userId
        String userInfo = (String) httpRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long userId = Long.parseLong(object.get("uid").toString());
        request.setUserId(userId);
        CreateOrderResponse response = orderCoreService.createOrder(request);
        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            // 执行成功，直接返回前端需要的数据
            return new ResponseUtil().setData(response.getOrderId());
        }
        // 调用失败
        return  new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @GetMapping("/shopping/order")
    public ResponseData getOrderList(Integer size, Integer page, String sort, HttpServletRequest httpRequest) {
        OrderListRequest request = new OrderListRequest();
        String userInfo = (String) httpRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long userId = Long.parseLong(object.get("uid").toString());
        request.setUserId(userId);
        request.setSize(size);
        request.setPage(page);
        request.setSort(sort);
        OrderListResponse response = orderQueryService.orderList(request);
        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            // 执行成功，直接返回前端需要的数据
            return new ResponseUtil().setData(response);
        }
        // 调用失败
        return  new ResponseUtil().setErrorMsg(response.getMsg());
    }

}
